package com.o2o.app.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import android.os.Environment;

/**
 * 文件工具类
 * 
 * @author wangyuehong
 * 
 */
public class FileUtil {
	// : data/data文件夹名
	public static String folder = "/data/data/com.haidilao/haidilao";
	
	public static String SDPATH;
	
	static
	{
		SDPATH = Environment.getExternalStorageDirectory() + "/";  
	}

	/**
	 * 将文件转换成的二进制流
	 * 
	 * @param file
	 *            文件对象
	 * @return buffer 文件的二进制流
	 */
	public static byte[] getFileBytes(String path) {
		File file = new File(path);
		FileInputStream inputStream = null;
		ByteArrayOutputStream outputStream = null;
		int bufferSize = 1024 * 10;
		byte[] buffer = new byte[bufferSize];
		int len = -1;
		try {
			if (file.isFile() && file.exists()) {
				inputStream = new FileInputStream(file);
				outputStream = new ByteArrayOutputStream();
				while ((len = inputStream.read(buffer)) != -1) {
					outputStream.write(buffer, 0, len);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return outputStream.toByteArray();
	}

	/**
	 * 将文件流转换成二进制流
	 * 
	 * @param is
	 *            文件流
	 * @return 二进制流
	 */
	public static byte[] getFileBytes(InputStream is) {
		ByteArrayOutputStream outputStream = null;
		int bufferSize = 1024 * 10;
		byte[] buffer = new byte[bufferSize];
		int len = -1;
		try {
			outputStream = new ByteArrayOutputStream();
			while ((len = is.read(buffer)) != -1) {
				outputStream.write(buffer, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return outputStream.toByteArray();
	}

	// 创建文件夹
	public static File mkdirBluetooth(String fileDir) {
		try {
			// 创建目标目录
			File targetDir = new File(fileDir);
			if (!targetDir.exists()) {
				if (!targetDir.mkdirs())
					return null;
			}
			// 返回目标目录文件
			return targetDir;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 在SD卡中创建文件
	 * 
	 * @param fileName
	 * @return
	 */
	public static File creatSDFile(String fileName)
	{  
        File file = new File(SDPATH + fileName);  
        
        try
		{
			file.createNewFile();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        return file;  
    } 
	
    /** 
     * 在SD卡上创建目录 
     *  
     * @param dirName 
     */  
    public static File creatSDDir(String dirName) {  
        File dir = new File(SDPATH + dirName);  
        dir.mkdir();  
        return dir;  
    }  
}
